<template>
  <div id="top">
    <div class="top_logo"  ></div>
    <div class="top_bar">
      <template v-for="item in topNav">
        <div
          v-if="item.showNav"
          :class="item.active ? 'top_menu_active' : ''"
          :id="item.id"
          @click="showPage(item)"
          class="top_menu"
        >{{ item.name }}</div>
      </template>

      <!--用户-->
      <div class="top_work">
        <!--头像和姓名-->

        <div class="top_name" @click="showWorkList()">
          {{ user.nickName }}
          <div class="top_portrait"></div>
          <div class="top_more"></div>
        </div>
        <!--下拉列表-->
        <div class="top_list" tabindex="1">
          <!--<div class="top_li" data-id="1"
			  			 :class="overWorkId==1? 'top_li_over':''">
			  			我的个人中心
          </div>-->
          <div
            class="top_li"
            data-id="2"
            @click="changePassword()"
            :class="overWorkId == 2 ? 'top_li_over' : ''"
          >修改密码</div>
          <div
            class="top_li"
            @click="logout()"
            data-id="3"
            :class="overWorkId == 3 ? 'top_li_over' : ''"
          >退出</div>
          <div
            class="top_li"
            v-if="debug"
            @click="openDebug()"
            data-id="4"
            :class="overWorkId == 4 ? 'top_li_over' : ''"
          >调试服务</div>
          <div
            class="top_li"
            v-if="roleMode != 0 && user.orgList.length > 1"
            @click="selectOrg()"
            data-id="5"
            :class="overWorkId == 5 ? 'top_li_over' : ''"
          >切换机构</div>
        </div>
      </div>

      <div class="downloadBtb" style="cursor: not-allowed;" v-show="messageVisible">
        <img style="width:0.26rem;" src="~@/assets/img/top/top_message.png">
      </div>
      <el-divider class="dividerLine" v-if="orgEntrySchool" direction="vertical"></el-divider>
      <!-- 返回机构 -->
      <div class="downloadBtb" v-if="orgEntrySchool" title="返回机构">
        <img src="~@/assets/img/top/home.png" @click="backToOrg">
      </div>
      <el-divider class="dividerLine" direction="vertical"></el-divider>

      <!--校区-->
      <div class="top_campus" v-if="campus&&roleMode==2" >
        <div class="top_campus_name" @click="showCampusList()">
          {{currentCampusName}}
          <div class="top_more"></div>
        </div>
        <!--下拉列表-->
        <div class="top_list" tabindex="1" :style="{marginLeft: marginLeft}">
          <div class="search_div">
            <el-input
              v-model="searchName"
              class="search_input"
              placeholder="搜索校区"
              prefix-icon="el-icon-search"
              clearable
            ></el-input>
          </div>
          <div class="top_scroll">
            <div
              v-for="item in campusSearchList" :key="item.campusId"
              @click="selectCampus(item)"
              :data-id="item.campusId"
              class="top_li"
              :class="[item.campusId == overCampusId ? 'top_li_over' : '', item.campusId == campus.campusId ? 'top_li_active' : '']"
            >{{item.name}}</div>
          </div>
        </div>
      </div>
      <!--机构-->
      <div class="top_campus" v-else-if="campus&&roleMode==1" >
        <div class="top_campus_name" @click="showCampusList()">
          机构管理后台系统
          <div class="top_more"></div>
        </div>
        <!--下拉列表-->
        <div class="top_list" tabindex="1" :style="{marginLeft: marginLeft}">
          <div class="search_div">
            <el-input
              v-model="searchName"
              class="search_input"
              placeholder="搜索校区"
              prefix-icon="el-icon-search"
              clearable
            ></el-input>
          </div>
          <div class="top_scroll">
            <div
              v-for="item in campusSearchList" :key="item.campusId"
              @click="entryCampus(item)"
              :data-id="item.campusId"
              class="top_li"
              :class="[item.campusId == overCampusId ? 'top_li_over' : '', item.campusId == campus.campusId ? 'top_li_active' : '']"
            >{{item.name}}</div>
          </div>
        </div>
      </div>
      <!--系统管理员-->
      <div class="top_campus" v-else-if="roleMode==0">
        <div class="top_campus_name" style="padding:0;">
          威校系统管理后台
        </div>
      </div>

    </div>
    <el-dialog
      title="修改密码"
      :visible.sync="dialogFormVisible"
      center
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px" class="demo-ruleForm">
        <el-form-item label="旧密码">
          <el-input
            style="width:80%"
            ref="password"
            clearable
            v-model="changePwd.password"
            placeholder="请输入旧密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input
            style="width:80%"
            ref="newPassword"
            v-model="changePwd.newPassword"
            type="password"
            autocomplete="new-password"
            show-password
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input
            style="width:80%"
            ref="checkPassword"
            v-model="changePwd.checkPassword"
            type="password"
            autocomplete="new-password"
            show-password
            placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCofim()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="调试服务" :visible.sync="isOpenDebug" width="6rem">
      <span class="ip_label">服务地址</span> &emsp;
      <el-input v-model="baseUrl" class="ip_input" spellcheck="false" clearable></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isOpenDebug = false">取 消</el-button>
        <el-button type="primary" @click="closeDebug()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {mapState,mapGetters,mapActions} from 'vuex'; //先要引入
import menuTool from "@/js/common/menu";
import relogin from "@/js/common/org_relogin";

var vm, $search, $campusScroll, $campusList, $workList;
export default {
  props:['setlogo'],
  data: function() {
    return {
      user: {},
      campusList: null,
      campus: null,
      overCampusId: null,
      overWorkId: null,
      searchName: "", //搜索的校区名
      debug: config.debug,
      baseUrl: null,
      isOpenDebug: false,
      dialogFormVisible: false,
      changePwd: {
        password: "",
        newPassword: "",
        checkPassword: ""
      },
      marginLeft: "",
      messageVisible:true,
      campusListVisible:true,
    };
  },
  computed: {
    topNav: function() {
      return this.$store.state.topNav;
    },
    campusSearchList: function() {
      //去首尾空格
      var name = this.searchName.trim();
      if (!name) {
        return this.campusList;
      }
      //循环校区列表,找到匹配项
      var list = [];
      this.campusList.forEach(function(item) {
        if (item.name.indexOf(name) >= 0) {
          list.push(item);
        }
      });
      return list;
    },
    currentCampusName:function(){
      let name='';
      this.campusList.forEach(function(item) {
        if (item.campusId == vm.campusId) {
          name=item.name;
        }
      });
      return name;
    },
    ...mapState({
      orgEntrySchool:state=>state.top.orgEntrySchool,
      roleMode:state=>state.roleMode,
      campusId:state=>state.campusId,
    }),
  },
  methods: {
    showPage: function(item) {
      //记录当前三级菜单的选中状态
      vm.$store.state.topNav.forEach(function(li) {
        li.active = false;
      });
      item.active = true;
      router.push(item.path);
    },
    showWorkList: function() {
      if ($workList.css("display") == "none") {
        vm.overWorkId = null;
        $workList.fadeIn(300);
        $workList.focus();
      }
    },
    showCampusList: function() {
      //校区列表隐藏的时候显示并聚焦
      if ($campusList.css("display") == "none") {
        vm.overCampusId = vm.campus.campusId;
        $campusList.fadeIn(300);
        $campusList.focus();
        //重置校区搜索框，滚回顶部
        vm.searchName = "";
        $campusScroll.scrollTop(0);
      }
      //不隐藏的时候执行该方法以及触发失焦事件了,执行隐藏
    },
    selectCampus: function(campus) {
      //关闭校区列表
      $campusList.fadeOut(300);
      //校区没改变,不处理
      if (vm.campus == campus) {
        return;
      }
      //校区id保存至状态管理
      vm.$store.commit("setCampusId", campus.campusId);
      //执行回调传回父页面
      vm.$emit("campusChange", campus.campusId);
      if (vm.user.roleMode > 1) {
        vm.setIconLogo();
      }
      //将校区重新排序,选中的放第一个
      let list = tool.clone(vm.campusList);
      let index = vm.campusList.indexOf(campus);
      list.unshift(list.splice(index, 1)[0]);
      //更新校区对象
      vm.campus = list[0];

      //保存进localStorage,以便下次刷新还在
      vm.user.campusList = list;
      tool.setItem(lsKey.user, vm.user, true);
      //隐藏后更新当前校区顺序
      setTimeout(function() {
        vm.campusList = list;
      }, 300);
    },
    /**机构进入校区 */
    entryCampus: function(campus) {
      //关闭校区列表
      $campusList.fadeOut(300);
      relogin({orgEntrySchool:true,campusId:campus.campusId},this,menuTool);
    },
    /**进入校区后返回机构 */
    backToOrg(){
      relogin({orgEntrySchool:false,campusId:null},this,menuTool);
    },
    addCofim: function() {
      var rules = [];
      let password = this.$refs.password;
      let newPassword = this.$refs.newPassword;
      let checkPassword = this.$refs.checkPassword;
      rules.push({
        judge: vm.changePwd.password,
        focus: password,
        tips: "请输入旧密码"
      });
      rules.push({
        judge: vm.changePwd.newPassword,
        focus: newPassword,
        tips: "请输入新密码"
      });
      rules.push({
        judge: vm.changePwd.checkPassword,
        focus: checkPassword,
        tips: "请再次输入新密码"
      });
      rules.push({
        judge: vm.changePwd.checkPassword === vm.changePwd.newPassword,
        focus: checkPassword,
        tips: "两次输入的新密码不一致"
      });
      rules.push({
        judge: tool.judge("password", vm.changePwd.newPassword),
        focus: newPassword,
        tips: tips.password
      });
      if (!tool.validate(rules)) {
        return;
      }
      api.changePwd(vm.changePwd).then(function(data) {
        if (data.resultCode == 2000) {
          vm.$message({
            message: "修改成功",
            type: "success"
          });
          api.logout({}).then(function() {
            tool.removeItem(lsKey.token);
            vm.$store.commit("clearAll");
            router.push("/login");
          });
        } else {
          vm.$message.error(data.message);
        }
      });
    },
    campusUpdate: function() {
      api.loginUser().then(function(data) {
        //保存最新用户信息,获取校区列表
        tool.setItem(lsKey.user, data.user, true);
        vm.campusList = data.user.campusList;

        //用户没有关联校区
        if (vm.campusList.length == 0) {
          //平台管理员
          if (data.user.roleMode == 0) {
            vm.campus = null;
            vm.$store.commit("setCampusId", null);
            vm.$emit("campusChange", null);
          } else {
            //其他角色不能没有校区,退出登录,跳转登录页
            api.logout({}).then(function() {
              tool.removeItem(lsKey.token);
              vm.$store.commit("clearAll");
              router.push("/login");
            });
          }
          return;
        }
        //用户有关联校区
        var campusId = vm.campus.campusId;
        vm.campus = null;
        //从新的校区列表找到当前校区,更新校区对象
        vm.campusList.forEach(function(item) {
          if (item.campusId == campusId) {
            vm.campus = item;
          }
        });
        //当前校区没有在校区列表中,可能被删或禁用了,更换校区
        if (vm.campusList.length > 0 && vm.campus == null) {
          //默认第一个为当前校区
          vm.campus = vm.campusList[0];
          //校区id保存至状态管理
          vm.$store.commit("setCampusId", campus.campusId);
          //执行回调传回父页面
          vm.$emit("campusChange", campus.campusId);
        }
      });
    },
    logout: function() {
      tool
        .confirm("确认退出?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(function() {
          api.logout({}).then(function() {
            tool.removeItem(lsKey.token);
            vm.$store.commit("clearAll");
            router.push("/login");
          });
        });
    },
    changePassword: function() {
      vm.dialogFormVisible = true;
    },
    openDebug: function() {
      vm.isOpenDebug = true;
      vm.baseUrl = config.baseUrl;
    },
    closeDebug: function() {
      vm.isOpenDebug = false;
      config.baseUrl = vm.baseUrl;
      axios.defaults.baseURL = vm.baseUrl;
    },
    setIconLogo: function() {
      var $icon = $("#link_icon");
      var $logo = $(".top_logo");
      //当前用户为机构管理员
      if (vm.user.roleMode == 1) {
        api.orgInfo({ orgId: vm.user.orgId }).then(function(d) {
          if (d.result == "操作成功") {
			  //当前用户所在的机构有上传logo
            if (d.organization.logoLinker != "") {
              let iconUrl = d.organization.logoLinker.split(",")[0];
              let logoUrl = d.organization.logoLinker.split(",")[1];
              $icon.attr("href", iconUrl);
              $logo.css("background-image", "url(" + logoUrl + ")");
              return;
            }
          }
        });
      } else {
		  //当前用户为校区级并且所在校区有上传logo
        if (vm.campus != null && vm.campus.icon != "") {
          let iconUrl = vm.campus.icon.split(",")[0];
          let logoUrl = vm.campus.icon.split(",")[1];
          $icon.attr("href", iconUrl);
          $logo.css("background-image", "url(" + logoUrl + ")");
          return;
        }else if ( vm.campus != null && vm.campus.icon == "") {
          api.orgInfo({ orgId: vm.user.orgId }).then(function(d) {
            if (d.result == "操作成功") {
              //当前用户所在的机构有上传logo
              if (d.organization.logoLinker != "") {
                let iconUrl = d.organization.logoLinker.split(",")[0];
                let logoUrl = d.organization.logoLinker.split(",")[1];
                $icon.attr("href", iconUrl);
                $logo.css("background-image", "url(" + logoUrl + ")");
                return;
              }
            }
          });
        }
      }

      //没有上传logo,改回默认
      $icon.attr("href", "./static/img/logo.png");
      $logo.css(
        "background-image",
        "url(" + require("@/assets/img/common/top_logo.png") + ")"
      );
    },
    hideMessage(){
      this.messageVisible=false;
    },
    hideCampusList(){
    //   this.campusListVisible=false;
    },
    selectOrg(){
      vm.user = tool.getItem(lsKey.user, true);
      if(vm.user.isAttaching=='1'){
        relogin({orgEntrySchool:false,campusId:''},this,menuTool,function(){
          router.push('/selectOrg');
        });
      }
      else{
        router.push('/selectOrg');
      }
      
    }
  },
  mounted: function() {
    $campusScroll = $(".top_scroll");
    $workList = $(".top_work .top_list");
    $search = $(".search_input input");

    var $li = $(".top_work .top_li");
    //列表失去焦点隐藏
    $workList.blur(function() {
      $(this).fadeOut(300);
    });
    //添加鼠标覆盖样式
    $li.mouseover(function(event) {
      vm.overWorkId = $(event.target).attr("data-id");
    });
    //根据机构名称设置图标
    if(this.setlogo)
      vm.setIconLogo();
  },
  created: function() {
    vm = this;
    vm.user = tool.getItem(lsKey.user, true);
    vm.user.orgList = vm.user.orgList || [];
    //获取校区列表(空数组则不设当前校区对象,页面不显示校区组件)
    vm.campusList = vm.user.campusList;

    if (vm.campusList.length > 0) {
      //默认第一个为当前校区
      vm.campus = vm.campusList[0];
    }

    vm.$nextTick(function() {
      $campusList = $(".top_campus .top_list");
      var $li = $(".top_campus .top_li");
      var width = $campusList.width();
      vm.marginLeft = "-" + width / 2 + "px";

      //列表失去焦点
      $campusList.blur(function() {
        var $this = $(this);
        setTimeout(function() {
          //不是搜索框获取焦点,隐藏
          if (!$search.is(":focus")) {
            $this.fadeOut(300);
          }
        }, 0);
      });
      //搜索框失去焦点
      $search.blur(function() {
        setTimeout(function() {
          //不是列表获取焦点,隐藏
          if (!$campusList.is(":focus")) {
            $campusList.fadeOut(300);
          }
        }, 0);
      });
      //添加鼠标覆盖样式
      $campusList.on("mouseover", ".top_li", function() {
        vm.overCampusId = $(event.target).attr("data-id");
      });
    });
  }
};
</script>

<style scoped src="@/style/common/top.css"></style>
<style lang="scss">
#top {
  .el-input__inner {
    border-radius: 0.08rem;
    font-size: 0.16rem;
    color: #666666;
    height: 0.36rem !important;
    line-height: 0.36rem;
  }
  .el-input__icon {
    line-height: 0.36rem;
  }

  .input_search {
    .el-input__inner {
      background-color: rgb(247, 248, 250);
    }
  }

  .downloadBtb{
    position: relative;
    float: right;
    width: 0.3rem;
    height: 0.4rem;
    margin-top: 0.25rem;
    margin-right: 0.1rem;
    font-size: 0.3rem;
    img{
      width: 0.3rem;
      height: 0.3rem;
    }

  }
  .downloadBtb:hover{
    cursor: pointer;
    // color: #5cb6ff;
    opacity: 0.8;
  }
  .dividerLine{
    float: right;
    height: 0.45rem;
    margin: 0.2rem 0.2rem 0 0.1rem;
  }
  .top_campus{
    min-width:unset;
    padding: unset;
    margin-right: 0.1rem;
    .top_campus_name{
      padding: 0 0.2rem;
      .top_more{
        right: 0;
      }
    }
  }
}
.box-top-download-popover{
    width: 100%;
    .dw-title{
      width: 100%;
      padding: 0.1rem 0;
      text-align: center;
      font-size: 0.18rem;
    }
    div{
      width: 100%;
    }
    .qrcode{
      height:1.7rem;
      img{
        width: 100%;
        height: auto;
        border: 0.01rem solid #e4dfdf;
      }
    }
  }
</style>
